package org.linlinjava.litemall.core.assertAdvice;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.core.exception.ServiceException;
import org.linlinjava.litemall.core.exception.enums.GlobalErrorCodeConstants;
import org.linlinjava.litemall.core.pojo.CommonResult;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class ErrorAdvice {

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(Exception ex) {
        //如果是异常报错就直接返回 如果是断言报错就返回失败格式
        if (ex instanceof ServiceException) {
            return serviceExceptionHandler((ServiceException) ex);
        }
        if(ex instanceof IllegalArgumentException||ex instanceof MybatisPlusException){
            return JSONUtil.toBean(ex.getMessage(),ResponseUtil.Response.class);
        }if(ex instanceof SQLException){
            return JSONUtil.toBean(ex.getMessage(),ResponseUtil.Response.class);
        }else {
            ex.printStackTrace();
        }
       return GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;
    }

    /**
     * 处理业务异常 ServiceException
     *
     * 例如说，商品库存不足，用户手机号已存在。
     */
    @ExceptionHandler(value = ServiceException.class)
    public CommonResult<?> serviceExceptionHandler(ServiceException ex) {
        log.info("[serviceExceptionHandler]", ex);
        return CommonResult.error(ex.getCode(), ex.getMessage());
    }

}
